<template>
  <div>
    <el-row>
      <el-col :span="24" v-if="showKeyInput">
        <el-form-item-plus
          :label="$t('menu.admin.lang.field.lang_key', '多语言键名')"
          :prop="keyProp"
          :tooltipContent="
            $t(
              'menu.admin.lang.tip.lang_key',
              '请先载入翻译数据，如无翻译数据，可以自定义翻译数据',
            )
          "
        >
          <div class="flex w-[100%]">
            <el-input
              v-model="langKey"
              :placeholder="
                getPlaceholder('menu.admin.lang.field.lang_key', '多语言键名')
              "
              @input="handleKeyInput"
            />
            <el-button
              type="success"
              class="ml-2"
              @click="handleGetTransData"
              :loading="loading"
            >
              {{ $t('common.action.load', '加载') }}
            </el-button>
          </div>
        </el-form-item-plus>
      </el-col>
      <el-col :span="12" v-for="lang in languages" :key="lang.code">
        <el-form-item-plus
          :label="getLanguageLabel(lang.code)"
          :prop="propPrefix ? `${propPrefix}.${lang.code}` : undefined"
          :rules="
            required
              ? [
                  {
                    required: true,
                    message: $t(
                      'menu.admin.lang.placeholder.translate',
                      '请输入{lang}翻译',
                      {
                        lang: getLanguageLabel(lang.code),
                      },
                    ),
                    trigger: 'blur',
                  },
                ]
              : []
          "
        >
          <el-input
            v-model="translations[lang.code]"
            :placeholder="
              $t('menu.admin.lang.placeholder.translate', '请输入{lang}翻译', {
                lang: getLanguageLabel(lang.code),
              })
            "
            clearable
            @input="handleInput"
          />
        </el-form-item-plus>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { LanguageEnum } from '@/enums';
import { smartTranslate as $t } from '@/lang';

// Props定义
const props = defineProps({
  // 语言代码数组
  languages: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 绑定值对象 { 'zh-cn': '中文内容', 'en': 'English Content' }
  modelValue: {
    type: Object,
    default: () => ({}),
  },
  // 是否必填
  required: {
    type: Boolean,
    default: false,
  },
  // 表单验证属性前缀
  propPrefix: {
    type: String,
    default: '',
  },
  // 是否显示语言键输入框和加载按钮
  showKeyInput: {
    type: Boolean,
    default: false,
  },
  // 语言键的值
  keyValue: {
    type: String,
    default: '',
  },
  // 语言键的表单验证属性
  keyProp: {
    type: String,
    default: 'key',
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false,
  },
});

// Emits定义
const emit = defineEmits([
  'update:modelValue',
  'change',
  'update:keyValue',
  'getTransData',
]);

// 响应式数据
const translations = ref({});
const langKey = ref('');

// 语言标签映射
const languageLabels = LanguageEnum.ALL.reduce((acc, current) => {
  acc[current.value] = current.label;
  return acc;
}, {});

// 获取语言标签
const getLanguageLabel = (code) => {
  return languageLabels[code] || code.toUpperCase();
};

// 获取占位符文本
const getPlaceholder = (key) => {
  return $t('common.message.placeholder.general', '请输入{field} ！', {
    field: $t(key),
  });
};

// 初始化翻译对象
const initTranslations = () => {
  const newTranslations = {};
  props.languages.forEach((lang) => {
    newTranslations[lang.code] = props.modelValue[lang.code] || '';
  });
  translations.value = newTranslations;
};

// 监听languages变化
watch(
  () => props.languages,
  () => {
    initTranslations();
  },
  { immediate: true, deep: true },
);

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && typeof newVal === 'object') {
      const newTranslations = {};
      props.languages.forEach((lang) => {
        newTranslations[lang.code] = newVal[lang.code] || '';
      });
      translations.value = newTranslations;
    }
  },
  { immediate: true, deep: true },
);

// 监听keyValue变化
watch(
  () => props.keyValue,
  (newVal) => {
    langKey.value = newVal || '';
  },
  { immediate: true },
);

// 处理翻译输入变化
const handleInput = () => {
  const result = { ...translations.value };
  emit('update:modelValue', result);
  emit('change', result);
};

// 处理语言键输入变化
const handleKeyInput = () => {
  emit('update:keyValue', langKey.value);
};

// 处理获取翻译数据按钮点击
const handleGetTransData = () => {
  emit('getTransData');
};

// 暴露方法给父组件
defineExpose({
  getTranslations: () => ({ ...translations.value }),
  setTranslations: (values) => {
    if (values && typeof values === 'object') {
      translations.value = { ...values };
      handleInput();
    }
  },
  // 兼容性方法：获取数组格式的翻译值
  getTranslationsArray: () => {
    return props.languages.map((lang) => translations.value[lang.code] || '');
  },
  // 兼容性方法：设置数组格式的翻译值
  setTranslationsArray: (values) => {
    if (Array.isArray(values)) {
      const newTranslations = {};
      props.languages.forEach((lang, index) => {
        newTranslations[lang.code] = values[index] || '';
      });
      translations.value = newTranslations;
      handleInput();
    }
  },
  // 获取语言键
  getKey: () => langKey.value,
  // 设置语言键
  setKey: (value) => {
    langKey.value = value || '';
    handleKeyInput();
  },
});
</script>

<style scoped></style>
